package net.cyue.homework.student.management.util;

import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DataValidator {
    private static final Validator validator;
    static {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.getValidator();
        System.out.println("DataValidator 初始化完成");
    }

    /**
     * @return 返回错误内容，无错误返回 null
     * */
    public static Map<String, Object> validate(Object obj) {
        final var validationResultSet = validator.validate(obj);
        if (!validationResultSet.isEmpty()) {
            final var r1 = validationResultSet.iterator().next();
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("message", r1.getPropertyPath() + r1.getMessage());
            errorMap.put("time", new Date());
            return errorMap;
        }
        return null;
    }
}

